﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace MyCollection
{
    public partial class CollectForm : Form
    {
        public CollectForm()
        {
            InitializeComponent();
        }

        private void CollectForm_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“myCollectDataSet.CollectProgram”中。您可以根据需要移动或移除它。
            this.collectProgramTableAdapter.Fill(this.myCollectDataSet.CollectProgram);
            // TODO: 这行代码将数据加载到表“myCollectDataSet.CollectGoods”中。您可以根据需要移动或移除它。
            this.collectGoodsTableAdapter.Fill(this.myCollectDataSet.CollectGoods);
            // TODO: 这行代码将数据加载到表“myCollectDataSet.CollectProgram”中。您可以根据需要移动或移除它。
            this.collectProgramTableAdapter.Fill(this.myCollectDataSet.CollectProgram);

          
        }

        /// <summary>
        /// 项目行 从form1传进来用
        /// </summary>
        private MyCollectDataSet.CollectProgramRow programRow;

        public MyCollectDataSet.CollectProgramRow ProgramRow
        {
            get { return programRow; }
            set { programRow = value; }
        }

        
        private Collect collect;

        public Collect Collect
        {
            get { return collect; }
            set { collect = value; }
        }

        //添加项目
        private void button1_Click(object sender, EventArgs e)
        {
            
            ProductConfig programForm = new ProductConfig();
            programForm.Owner = this;
            //programForm.CurrentRow = this.myCollectDataSet.CollectProgram.NewCollectProgramRow();
            programForm.ShowDialog();

            if (this.collect != null)
            {
                this.myCollectDataSet.CollectProgram.AddCollectProgramRow(collect.CollectName, collect.CollectUrl, collect.IsUTF,
                    collect.ListStart, collect.ListOver, collect.HrefStart, collect.HrefOver,
                    collect.TitleStart, collect.TitleOver, collect.ConStart, collect.ConOver,
                    collect.ImgStart, collect.ImgOver, collect.PriceStart, collect.PriceOver, 0);

                //this.myCollectDataSet.CollectProgram.AddCollectProgramRow(programRow);
                UpdateMyDataSet();
            }
            
            
        }

        private void btn_Edit_Click(object sender, EventArgs e)
        {
            
           
            DataRowView rowView = collectProgramBindingSource1.Current as DataRowView;
            if (rowView == null)
            {
                return;
            }

            MyCollectDataSet.CollectProgramRow row = rowView.Row as MyCollectDataSet.CollectProgramRow;

            ProductConfig programForm = new ProductConfig();
            programForm.CurrentRow = row;
            programForm.ShowDialog();

            UpdateMyDataSet();
            
        }

        /// <summary>
        /// 更新CollectProgram表
        /// </summary>
        private void UpdateMyDataSet()
        {
            MyCollectDataSet.CollectProgramDataTable changTable = this.myCollectDataSet.CollectProgram.GetChanges() as MyCollectDataSet.CollectProgramDataTable;
            if (changTable != null)
            {
                this.collectProgramTableAdapter.Update(changTable);
                this.myCollectDataSet.AcceptChanges();
            }

           
            return;
        }

        /// <summary>
        /// 更新CollectGoods表
        /// </summary>
        private void UpdateChildRows()
        {
            MyCollectDataSet.CollectGoodsDataTable goodsChange = this.myCollectDataSet.CollectGoods.GetChanges() as MyCollectDataSet.CollectGoodsDataTable;
            if (goodsChange != null)
            {
                this.collectGoodsTableAdapter.Update(goodsChange);
                this.myCollectDataSet.AcceptChanges();
            }
            return;
        }

        #region 删除项目
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            DataRowView rowView = collectProgramBindingSource1.Current as DataRowView;
            if (rowView == null)
            {
                return;
            }

            MyCollectDataSet.CollectProgramRow row = rowView.Row as MyCollectDataSet.CollectProgramRow;

            MyCollectDataSet.CollectGoodsRow[] goodsRows = row.GetCollectGoodsRows();
            foreach (MyCollectDataSet.CollectGoodsRow goods in goodsRows)
            {
                goods.Delete();
            }
            UpdateChildRows();

            row.Delete();

            UpdateMyDataSet();
        }
        #endregion
        #region 开始采集
        private void button1_Click_1(object sender, EventArgs e)
        {
            DataRowView rowView = collectProgramBindingSource1.Current as DataRowView;
            if (rowView == null)
            {
                return;
            }
            
            MyCollectDataSet.CollectProgramRow row = rowView.Row as MyCollectDataSet.CollectProgramRow;

            RemoteHtml remote = new RemoteHtml(row);

            int goodsCount = remote.HrefCollection().Length;
            //设置进度条

            progressBar1.Value = 0;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = remote.HrefCollection().Length;
            progressBar1.Step = 1;
            label3.Text = "/" + progressBar1.Maximum.ToString();

            //MyCollectDataSet ds = myCollectDataSet;
            //this.collectGoodsTableAdapter.Fill(ds.CollectGoods);
            
            ////全都重新采集，这样可以保持最新
            //ds.CollectGoods.Clear();

            //设定Title为唯一列 不允许相同标题的商品
            this.myCollectDataSet.CollectGoods.TitleColumn.Unique = false;
            int okCount = 0;        //成功采集次数
            

            foreach (string goodsUrl in remote.HrefCollection())
            {
                try
                {
                    //标题没有重复
                    
                    string url = CollectClass.DefiniteUrl(goodsUrl, row.CollectUrl);
                    Commodity goods = new Commodity(row, url);
                    //string content = htmlTemplet.Replace("{$商品描述}", goods.Content);
                    //content = (content.Length > 25000 ? goods.Content : content);
                    myCollectDataSet.CollectGoods.AddCollectGoodsRow(row, url, goods.Title,
                        goods.Content, goods.Content, goods.ImgPath, goods.LocalImgPath,
                        Convert.ToDecimal(goods.Price), Convert.ToDecimal(CollectClass.GetPrice(goods.Price)));

                    okCount++;
                }
                catch (ConstraintException ex)
                {
                    
                }

                progressBar1.Value++;                
                label2.Text = progressBar1.Value.ToString();
                Application.DoEvents();
            }

            MyCollectDataSet.CollectGoodsDataTable changeTable =
                myCollectDataSet.CollectGoods.GetChanges() as MyCollectDataSet.CollectGoodsDataTable;

            if (changeTable != null)
            {
                collectGoodsTableAdapter.Update(changeTable);
                myCollectDataSet.AcceptChanges();
            }

            row.CollectNum = okCount + row.CollectNum;

            collectProgramTableAdapter.Update(row);

            MessageBox.Show("成功采集" + okCount.ToString() + "\r\n失败采集" + Convert.ToString((goodsCount - okCount)), "采集成功");
            //progressBar1.Value = 0;

        }

        #endregion

        private void btn_Copy_Click(object sender, EventArgs e)
        {
           
            DataRowView rowView = collectProgramBindingSource1.Current as DataRowView;
            if (rowView == null)
            {
                return;
            }
            else
            {
                MyCollectDataSet.CollectProgramRow row = (MyCollectDataSet.CollectProgramRow)rowView.Row ;

                MyCollectDataSet.CollectProgramRow addRow = myCollectDataSet.CollectProgram.NewCollectProgramRow();

                addRow.CollectName = row.CollectName;
                addRow.CollectNum = 0;
                addRow.CollectUrl = row.CollectUrl;
                addRow.HerfOverString = row.HerfOverString;
                addRow.HerfStartString = row.HerfStartString;
                addRow.TitleOverString = row.TitleOverString;
                addRow.TitleStartString = row.TitleStartString;
                addRow.ContStartString = row.ContStartString;
                addRow.ContOverString = row.ContOverString;
                addRow.ImgOverString = row.ImgOverString;
                addRow.ImgStartString = row.ImgStartString;
                addRow.PriceOverString = row.PriceOverString;
                addRow.PriceStartString = row.PriceStartString;
                addRow.ListOverString = row.ListOverString;
                addRow.ListStartString = row.ListStartString;
                addRow.IsUtf = row.IsUtf;


                myCollectDataSet.CollectProgram.AddCollectProgramRow(addRow);
                UpdateMyDataSet();
            }
            
        }

        //显示数据
        private void button3_Click(object sender, EventArgs e)
        {
            DataRowView rowView = collectProgramBindingSource1.Current as DataRowView;
            if (rowView == null)
            {
                return;
            }

            MyCollectDataSet.CollectProgramRow row = rowView.Row as MyCollectDataSet.CollectProgramRow;

            DisplayGoods display = new DisplayGoods();
            display.CurrentRow = row;
            display.ShowDialog();

            //如果有行改变 就重新填充myCollectDataSet.CollectGoods
            if (display.TableChange != null)
            {
                collectGoodsTableAdapter.Fill(myCollectDataSet.CollectGoods);
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataRowView rowView = collectProgramBindingSource1.Current as DataRowView;
            if (rowView == null)
            {
                return;
            }

            MyCollectDataSet.CollectProgramRow row = rowView.Row as MyCollectDataSet.CollectProgramRow;

            MyCollectDataSet.CollectGoodsRow[] rows = row.GetCollectGoodsRows();
            string filePath = CollectSetting.Default.SaveCSVPath + row.CollectName + ".csv";
            StreamWriter sw = new StreamWriter(filePath,false, Encoding.Unicode);
            //读取宝贝模板
            string htmlTemplet = File.ReadAllText(CollectSetting.Default["HtmlTemplet"].ToString());

            progressBar1.Value = 0;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = rows.Length;
            progressBar1.Step = 1;
            label3.Text = "/" + progressBar1.Maximum.ToString();

            sw.WriteLine();
            foreach (MyCollectDataSet.CollectGoodsRow goods in row.GetCollectGoodsRows())
            {
                
                string content = htmlTemplet.Replace("{$商品描述}", goods.Content);
                content = (content.Length > 25000 ? goods.Content : content);
                content = CollectClass.GetStringByNoSpace(content);
                string contents = "";
                contents = contents + "\"" + goods.Title + "\"\t";
                contents = contents + "50010810\t44251086\t5\t\"上海\"\t\"上海\"\t\"b\"\t";
                contents = contents + goods.NewPrice.ToString() + "\t";
                contents = contents + "0.000000\t1000\t7\t1\t10.000000\t20.000000\t5.000000\t0\t1\t0\t0\t1\t0\t0\t";
                contents = contents + "\"1980-1-1  0:00:00\"\t\"\"\t";
                contents = contents + "\"" + content + "\"\t";
                contents = contents + "\"" + goods.ImgLocalPath + "\"\t";
                contents = contents + "\"34580:27133;34581:20165;34582:10122;30964:96241;\"\t";
                contents = contents + "0.000000\t0\t0\t0\t\"2008-07-11 13:56:37\"\t100\t0\t";

                
                sw.WriteLine(contents);

                progressBar1.Value++;
                label2.Text = progressBar1.Value.ToString();
                Application.DoEvents();
            }
            sw.Close();
            MessageBox.Show("导出宝贝成功，导出文件为：" + filePath);
           
        }

        private void btn_Setting_Click(object sender, EventArgs e)
        {
            FormSetting setting = new FormSetting();
            setting.ShowDialog();
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            DisplayGoods display = new DisplayGoods();
            display.TableChange = this.myCollectDataSet.CollectGoods;
            display.ShowDialog();

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            ProjectConfig config = new ProjectConfig();
            config.ShowDialog();
        }
    }
}